package simpleSpring.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * mybatis通过自定义FactoryBean来实现interface访问sql的代理对象
 *
 * @author caihe
 * @date 2022/10/25 17:24
 */
//@Component
public class CaiheFactoryBean implements FactoryBean {

    private SqlSession sqlSession;

    private Class mapperClazz;

    public CaiheFactoryBean(Class clazz) {
        this.mapperClazz = clazz;
    }

    @Autowired
    public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(mapperClazz);
        this.sqlSession = sqlSessionFactory.openSession();
    }

    @Override
    public Object getObject() throws Exception {
        return sqlSession.getMapper(mapperClazz);
    }

    @Override
    public Class<?> getObjectType() {
        return mapperClazz;
    }
}
